import { useIntl, useModel } from "@umijs/max"
import { App, Button, Table } from "antd"
import type { AlignType } from "rc-table/lib/interface"
import React, { CSSProperties, useEffect, useState } from "react"

// 标题统一样式
const headerStyle: CSSProperties = {
  textAlign: "center" as const,
  fontWeight: 650,
  fontSize: "15px",
  color: "#000"
}

const AlarmRecordsForm: React.FC = () => {
  const { message } = App.useApp()
  const [currentPage, setCurrentPage] = useState(1)
  const { alarmRecords, updateProduceData } = useModel("produceModel")
  const { callPy, wsIsOpenRef } = useModel("websocketModel")
  const [pageSize, setPageSize] = useState(3) // 每页显示的报警信息
  const [isReload, setIsReload] = useState(false)
  const intl = useIntl()

  useEffect(() => {
    console.log("AlarmRecordsForm 表单初始化,isReload:", isReload)
    const fetchData = async () => {
      try {
        const response = await callPy("db", "get_alarm_records_from_web", [])
        if (response.state) {
          updateProduceData({ alarmRecords: response.data })
        } else {
          message.error("表单数据获取失败:" + response.info)
          updateProduceData({ alarmRecords: [] })
        }
      } catch (error) {
        console.log("数据加载失败", error)
      }
    }

    if (wsIsOpenRef.current) {
      fetchData()
    } else {
      // 过1秒之后再尝试获取数据
      setTimeout(() => {
        fetchData()
      }, 500)
    }
  }, [isReload])

  // 获取当前页数据
  const getCurrentPageData = () => {
    const start = (currentPage - 1) * pageSize
    const end = currentPage * pageSize
    return alarmRecords.slice(start, end)
  }

  // 删除当前页所有记录
  const handleDeleteCurrentPage = async () => {
    const currentPageData = getCurrentPageData()
    const keys = currentPageData.map((item) => item.key)
    const response = await callPy("db", "delete_current_page_from_web", [keys])
    setIsReload(!isReload)
    if (response.state) {
      message.success(intl.formatMessage({ id: "alarmRecordsForm.deleteCurrentSuccess" }))
      updateProduceData(response.data)
    } else {
      message.error(
        intl.formatMessage({ id: "alarmRecordsForm.deleteCurrentFail" }) + response.info
      )
    }
  }

  // 删除所有记录
  const handleDeleteTotalPage = async () => {
    const response = await callPy("db", "delete_total_page_from_web", [])
    setIsReload(!isReload)
    if (response.state) {
      message.success(intl.formatMessage({ id: "alarmRecordsForm.clearAllSuccess" }))
      updateProduceData({ alarmRecords: [] })
    } else {
      message.error(
        intl.formatMessage({ id: "alarmRecordsForm.clearAllFail" }) + response.info
      )
    }
  }

  // 页码改变的回调
  const handlePageChange = (page: number) => {
    setCurrentPage(page)
  }

  const columns = [
    {
      title: (
        <span style={headerStyle}>
          {intl.formatMessage({ id: "alarmRecordsForm.happenTime" })}
        </span>
      ),
      dataIndex: "happenTime",
      width: "20%",
      ellipsis: true,
      align: "center" as AlignType
    },
    {
      title: (
        <span style={headerStyle}>
          {intl.formatMessage({ id: "alarmRecordsForm.alarmContent" })}
        </span>
      ),
      dataIndex: "alarmContent",
      width: "80%",
      ellipsis: true,
      align: "center" as AlignType,
      render: (text: string) => <span style={{ color: "#FA8C16" }}>{text}</span>
    }
  ]

  return (
    <>
      <Table
        className="alarm-records-table"
        bordered
        dataSource={alarmRecords}
        columns={columns}
        size="small"
        pagination={{
          pageSize: pageSize,
          onChange: handlePageChange,
          current: currentPage,
          showSizeChanger: false,
          position: ["bottomCenter"],
          showTotal: (total) => (
            <div style={{ display: "flex", alignItems: "center" }}>
              <span style={{ marginRight: 15 }}>
                {intl.formatMessage({ id: "alarmRecordsForm.total" }, { total })}
              </span>
              <Button type="primary" size="small" onClick={handleDeleteCurrentPage}>
                {intl.formatMessage({ id: "alarmRecordsForm.deleteCurrent" })}
              </Button>
              <Button
                type="primary"
                size="small"
                onClick={handleDeleteTotalPage}
                style={{ marginLeft: 15 }}
              >
                {intl.formatMessage({ id: "alarmRecordsForm.clearAll" })}
              </Button>
            </div>
          ),
          style: { margin: 0, padding: "8px 0" }
        }}
        style={{
          fontSize: "14px"
        }}
      />

      <style>
        {`
          .alarm-records-table .ant-table-thead > tr > th {
            background-color: #fafafa;
            text-align: center;
            padding: 8px 16px;
          }
          .alarm-records-table .ant-table-tbody > tr > td {
            text-align: center;
            color: #FA8C16;
            padding: 8px 16px;
          }
          .alarm-records-table .ant-pagination {
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0;
            padding: 8px 0;
          }
        `}
      </style>
    </>
  )
}

export default () => (
  <App>
    <AlarmRecordsForm />
  </App>
)
